package com.fuatnow.game.database;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

import java.sql.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * Created by fuatnow on 17/1/8.
 */
public class DBHelper {
    public static final String url = "jdbc:mysql://127.0.0.1:3306/";
    public static final String name = "com.mysql.jdbc.Driver";
    public static final String user = "root";
    public static final String password = "ning0428";

    private Connection conn ;
    private Statement state;


    private static DBHelper m_instance = null;
    private static Lock lock = new ReentrantLock();
    public static DBHelper getInstance()
    {
        if(m_instance == null)
        {
            lock.lock();
            if(m_instance == null){
                m_instance = new DBHelper("wanhai",password);
            }
            lock.unlock();
            lock = null;
        }
        return m_instance;
    }


    private DBHelper(String database_name,String password)
    {
        try {
            String fullUri = url+database_name;
            System.out.println(fullUri);
            conn = DriverManager.getConnection(fullUri, user, password);
            System.out.println("连接成功");
            state =conn.createStatement();
        } catch (SQLException e) {
            System.out.println("连接失败");
        }
    }

    public Statement getStatement()
    {
        return state;
    }
    public ResultSet getResultSet(String sql)
    {
        ResultSet resultSet = null;
        try {
            resultSet= state.executeQuery(sql);
        } catch (SQLException e) {
            System.out.println("getResultSet exception");
        }
        return resultSet;
    }

    public boolean setSql(String sql)
    {
        try {
            state.execute(sql);
        }catch(MySQLIntegrityConstraintViolationException e)
        {
            System.out.println("重复导入 ："+sql);
        }catch (SQLException e) {
            System.out.println("SetSql exception");
            e.printStackTrace();
            return false;
        }
        return true;
    }


    public void close() {
        try {
            this.conn.close();
            this.state.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
